package com.iot.iotplus.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;

import java.security.SecureRandom;

public class SendVerificationCodeUtil {

    private static final String ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI5tEfN7XH8f25vabFEeQj";
    private static final String ALIBABA_CLOUD_ACCESS_KEY_SECRET = "JmnJHjNYkCv8p4O2a5HhE6md8smbdV";

    public static SendSmsResponse sendCode(String phoneNumber){
//        String phoneNumber = "18272409561";

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        // 生成动态验证码
        SecureRandom random = new SecureRandom();
        String code = String.format("%06d", random.nextInt(1000000));
        // 创建API请求并设置参数
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_154950909");
        request.setPhoneNumbers(phoneNumber);
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        //将生成的验证码存入redis缓存
        Jedis jedis = new Jedis("47.98.63.69", 6379, 2000); // 这里填写你的Redis服务器地址
        // 存储验证码，设置过期时间为5分钟
        jedis.setex(phoneNumber, 5 * 60, code);
        String string = jedis.get(phoneNumber);

        SendSmsResponse response = null;
        try {
             response = client.getAcsResponse(request);
//            System.out.println(JSON.toJSON(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }finally {
//            jedis.close();
        }
        return response;
    }

    //获取redis缓存中的验证码
    public static String getCode(String phoneNumber){
        Jedis jedis = new Jedis("47.98.63.69", 6379, 2000); // 这里填写你的Redis服务器地址
        String code = jedis.get(phoneNumber);
        jedis.close();
        return code;
    }

    //验证码校验
    public static boolean checkCode(String phoneNumber, String code){
        String redisCode = getCode(phoneNumber);
        if(redisCode == null){
            return false;
        }
        return redisCode.equals(code);
    }

}
